<?php
class dbt_shake extends sing_table{
    
    private $_G;
    private $_mid;
    private $_openid;
    private $_memberId;
    private $_moretype;
    private $_shake_id;
    private $_unionid;

    //构造方法
    function __construct(){
        global $_G;
        $this->_G = &$_G;
        $this->_mid = $_GET['mid'];
        $this->_moretype = array(3, 4, 5);
    }
    
    //转换插入和读取的数据
    public function dataTurn($data="",$type="set"){
        if($type=="set"){
            if(is_array($data)){
                $lastData = "array|||".array2string($data);
            }else{
                $lastData = "string|||".$data;
            }
        }else if($type=="get"){
            if(is_array($data)){
                return $data;
            }
            $nowData = explode("|||", $data);
            if($nowData[0]=="array"){
                $lastData = string2array($nowData[1]);
            }else if($nowData[0]=="string"){
                $lastData = $nowData[1];
            }
        }
        return $lastData;
    }
    
    //插入主记录表
    public function insertLog($thisArr=array()){
        if(!$thisArr){
            return false;
        }

        var_dump($thisArr);
        echo '<br>';
        DB::SetMainDB(DB_ESHOP);
        $logId = DB::result_first("select id from %t where display=1 and mds=%s",array("es_shake_log",$thisArr['mds']));
        if(!$logId){
                
            $arr = $thisArr;

            $insert = array();
            $insert['mid'] = $this->_mid = $_GET['mid'] = $arr['mid'];
            $insert['gettime'] = $arr['inputtime'];
            $insert['inputtime'] = time();
            $insert['member_id'] = $this->_memberId = $_GET['memberId'] = $arr['member_id'];
            $insert['openid'] = $this->_openid = $_GET['openid'] = $arr['openid'];
            $insert['shake_id'] = $this->_shake_id = $_GET['shake_id'] = $arr['shake_id'];
            $insert['unionid'] = $this->_unionid = $_GET['unionid'] = $arr['unionid'];
            $insert['tableid'] = $arr['tableid'];
            $insert['tablename'] = $arr['tablename'];
            $insert['tabletype'] = $arr['tabletype'];
            $insert['price'] = $arr['price'];
            $insert['thumb'] = $arr['thumb'];
            $insert['prize_key'] = $arr['prize_key'];
            $insert['title'] = $arr['title'];
            $insert['mds'] = $arr['mds'];

            unset($arr["mid"],$arr["inputtime"],$arr['member_id'],$arr['openid'],$arr['shake_id'],$arr['tableid'],$arr['tablename'],$arr['tabletype'],$arr['thumb'],$arr['prize_key'],$arr['title'],$arr['mds']);

            $insert['prize_json'] = json_encode($arr);

            $logId = $this->insertData($insert,true);
        }else{
            $this->_mid = $_GET['mid'] = $thisArr['mid'];
            $this->_memberId = $_GET['memberId'] = $thisArr['member_id'];
            $this->_openid = $_GET['openid'] = $thisArr['openid'];
            $this->_shake_id = $_GET['shake_id'] = $thisArr['shake_id'];
            $this->_unionid = $_GET['unionid'] = $thisArr['unionid'];
        }
        
        if($logId){
            $updArr = array();
            switch($thisArr['tablename']){
                case "es_things" : //实物
                    break;
                case "es_cash_coupon" : //代金券
//                    $thisBool = $this->sendCashCoupon($thisArr);//
                    $thisBool = $this->sendCashMoney($thisArr);//支付宝发奖，先存记录，然后提现
                    if($thisBool){
                        $updArr['logtablename'] = "es_cash_coupon_sendlog";
                        $updArr['logtableid'] = $thisBool['thisId'];
                        $updArr['send_status'] = 1;
                        $updArr['updatetime'] = time();
                    }
                    break;
                case "es_group_coupon" : //会员券
                    break;
                case "es_coupon" : //优惠券
                    $thisId = $this->sendCoupon($thisArr);
                    if($thisArr['tableid']==309){
                        C::t("#shake#member")->setMemberGroupWithCard(6);
                    }
                    $updArr['logtablename'] = "es_coupon_log";
                    $updArr['logtableid'] = $thisId;
                    $updArr['send_status'] = $thisId?1:0;
                    $updArr['updatetime'] = time();
                    break;
            }
            if($updArr){
                $where = DB::format("id=%d", array($logId));
                $this->updData($updArr,$where);
            }
            return $logId;
        }
        
    }
    
    //添加表单信息
    public function getForm($key=""){
        if(!$key){
            return false;
        }
        
        $thisData = redis2("get",$key);
        return $this->dataTurn($thisData,"get");
    }
    //发现金到账户，支付提现
    public function sendCashMoney($thisArr=array(),$is_reissue = 0){

        $couponLogArr = array();
        $couponLogArr['cash_id'] = $thisArr['tableid'];
        $couponLogArr['inputtime'] = time();
        $couponLogArr['mid'] = $thisArr['mid'];
        $couponLogArr['member_id'] = $thisArr['member_id'];
        $couponLogArr['cash_title'] = $thisArr['title'];
        $couponLogArr['price'] = $thisArr['price'];
        $couponLogArr['shake_id'] = $thisArr['shake_id'];
        $couponLogArr['phone'] = $thisArr['phone'];
        DB::SetMainDB(DB_ESHOP);
        $thisId = DB::insert("es_cash_winning_prize", $couponLogArr ,true);
        if($thisId){
            return $thisId;
        }else{
            return false;
        }

    }
    //发送优惠券
    public function sendCoupon($thisArr=array()){
        if(!$thisArr){
            return false;
        }
        
        $couponLogArr = array();
        $couponLogArr['inputtime'] = time();
        $couponLogArr['mid'] = $thisArr['mid'];

        $couponLogArr['coupon_id'] = $thisArr['tableid'];
        $couponLogArr['openid'] = $thisArr['openid'];
        $couponLogArr['member_id'] = $thisArr['member_id'];
        $couponLogArr['gettype'] = 4;
        $couponLogArr['title'] = $thisArr['title'];

        $couponLogArr['store_id'] = $thisArr['store_id'];
        $couponLogArr['description'] = $thisArr['description'];
        $couponLogArr['thumb'] = $thisArr['thumb'];
        $couponLogArr['price'] = $thisArr['price'];
        $couponLogArr['limit_price'] = $thisArr['limit_price'];
        $couponLogArr['limit_user'] = $thisArr['limit_user'];
        $couponLogArr['btime'] = $thisArr['btime'];
        $couponLogArr['etime'] = $thisArr['etime'];
        $couponLogArr['limit_btime'] = $thisArr['limit_btime'];
        $couponLogArr['limit_etime'] = $thisArr['limit_etime'];
        $couponLogArr['no_discount_group'] = $thisArr['no_discount_group'];
        $couponLogArr['group_id'] = $thisArr['group_id'];
        $couponLogArr['type'] = $thisArr['type'];
        $couponLogArr['tagstr'] = $thisArr['tagstr'];
        $couponLogArr['is_activity'] = $thisArr['is_activity'];

        DB::SetMainDB(DB_ESHOP);
        $thisId = DB::insert("es_coupon_log", $couponLogArr,true);
        
        return $thisId;
    }
    
    //发送代金券
    public function sendCashCoupon($arr=array(),$is_reissue = 0){
        
        $nowArr = array();
        $nowArr['coupon_stock_id'] = $arr['coupon_stock_id'];  //代金券批次id
        $nowArr['openid_count'] = 1;  // openid记录数
        $nowArr['openid'] = $arr['openid'];  // 用户openid
        if($is_reissue){
            $nowArr['is_reissue'] = $is_reissue;
        }
        $thisId = $this->insertCashCouponSendLog($nowArr,true);
        if($is_reissue){
            unset($nowArr['is_reissue']);
        }
        $nowArr['thisId'] = $thisId;
        
        echo 'nowArr：\n';
        var_dump($nowArr);
        
        $_GET['mid'] = $this->_mid;
        
        $lastData = C::t("#shake#couponjsdk")->sendCoupon($nowArr);
        
        $upd = array();
        $upd['ask_time'] = $lastData['startTimeStamp'];
        $upd['return_time'] = $lastData['endTimeStamp'];
        $upd['return_json'] = json_encode($lastData);
        
        $where = DB::format("id=%d", array($thisId));
        
        $this->updateCashCouponSendLog($upd,$where);
        
        if($lastData['result_code']=='result_code'){
            $lastData['thisId'] = $thisId;
            return $lastData;
        }else{
            return false;
        }
    }
    //插入代金券发送记录
    public function insertCashCouponSendLog($data=array(),$thisBool=false){
        $data['inputtime'] = time();
        $data['mid'] = $this->_mid;
        DB::SetMainDB(DB_ESHOP);
        $thisId = DB::insert("es_cash_coupon_sendlog", $data ,$thisBool);
        return $thisId;
    }
    
    //修改代金券发送记录
    public function updateCashCouponSendLog($data=array(),$where=""){
        $data['updatetime'] = time();
        DB::SetMainDB(DB_ESHOP);
        $num = DB::update("es_cash_coupon_sendlog", $data , $where);
        return $num;
    }
    
    //插入数据
    public function insertData($data=array(),$thisBool=false){
        DB::SetMainDB(DB_ESHOP);
        $id = DB::insert("es_shake_log", $data , $thisBool);
        return $id;
    }
    
    //修改数据
    public function updData($data=array(),$where=""){
        DB::SetMainDB(DB_ESHOP);
        $num = DB::update("es_shake_log", $data , $where);
        return $num;
    }
    
    //添加信息
    public function act_order($tablename,$tableid,$ordername,$orderid,$info){ //$tablename：主表名称，$tableid：主表id，$ordername：记录表名称，$orderid：记录表id，$info：数据
        if(!$tablename || !$tableid || !$ordername || !$orderid || !$info){
            return array("Error"=>1,"Msg"=>"参数错误");
        }
        //初始化数据
        $insert = array();
        $public = array();
        //查找选项
        DB::SetMainDB(DB_MAIN);
        $act = DB::fetch_all('select id,type,name,ismust,pubid from %t where mid=%s and tablename=%s and tableid=%s and parentid=0 and display=1 order by turn desc,id asc',array('wx_act',$this->_mid,$tablename,$tableid));
        //遍历选项
        foreach($act as $k => $v){
            $value = $info['act'][$v['id']];
            //判断必填
            if($v['ismust'] && empty($value)){
                return array('Error' => 1,'Msg' =>$v['name'].' 为必填选项');
            }
            //判断 选项类型 是不是需要元素
            if(in_array($v['type'],$this->_moretype)){
                //如果没有值则不添加数据
                if(empty($value)) continue;
                //判断值是不是数组  
                if(is_array($value)){
                    //此处 类型为多选
                    $pubvaluearr = array();
                    foreach($value as $k_v=>$v_v){
                        DB::SetMainDB(DB_MAIN);
                        $option = DB::fetch_first('select id,name,pubid from %t where mid=%s and parentid=%d and id=%d and display=1 ',array('wx_act',$this->_mid,$v['id'],$v_v));	
                        //初始化 需要添加的数组
                        $insert[$v_v] = array();
                        $insert[$v_v]['value'] = $option['name'];
                        $insert[$v_v]['actid'] = $v_v;
                        $insert[$v_v]['actpid'] = $v['id'];	
                        $pubvaluearr[] = $option['name'];

                    }
                    $public[$k] = array();
                    $public[$k]['value'] = implode('<|!|>',$pubvaluearr);
                    $public[$k]['actpid'] = $v['pubid'];
                    $public[$k]['actid'] = 0;	
                }else{
                    //此处 类型为单选 和 下拉
                    DB::SetMainDB(DB_MAIN);
                    $option = DB::fetch_first('select id,name,pubid from %t where mid=%s and parentid=%d and id=%d and display=1 ',array('wx_act',$this->_mid,$v['id'],$value));
                    //初始化 需要添加的数组
                    $insert[$value] = array();
                    $insert[$value]['value'] = $option['name'];
                    $insert[$value]['actid'] = $value;
                    $insert[$value]['actpid'] = $v['id'];

                    $public[$k] = array();
                    $public[$k]['value'] = $option['name'];
                    $public[$k]['actpid'] = $v['pubid'];
                    $public[$k]['actid'] = 0;
                }

            }else{
                //初始化 需要添加的数组
                $insert[$k] = array();
                //此处类型为文本框和文本域
                $insert[$k]['value'] = $value;
                $insert[$k]['actid'] = $v['id'];
                $insert[$k]['actpid'] = $v['id'];

                $public[$k] = array();
                $public[$k]['value'] = $value;
                $public[$k]['actpid'] = $v['pubid'];
                $public[$k]['actid'] = $v['pubid'];
            }
        }
        //最后一次判断是否有logid
        $insert_log = array();
        $insert_log['_uid'] = $this->_G['_uid'];
        $insert_log['uid'] = $this->_G['uid'];
        $insert_log['mid'] = $this->_mid;
        $insert_log['openid'] = $this->_openid;
        $insert_log['member_id'] = $this->_memberId;
        $insert_log['tablename'] = $ordername;
        $insert_log['tableid'] = $orderid;
        $insert_log['tableparentid'] = 0;
        $insert_log['inputtime'] = TIME;
        $insert_log['status'] = 1;
        $insert_log['display'] = 1;
        DB::SetMainDB(DB_MAIN);
        $insert_id = DB::insert('wx_act_log',$insert_log,true);

        foreach($insert as $k=>$v){
            $insert_ext = array();
            $insert_ext = $v;
            $insert_ext['openid'] = $this->_openid;
            $insert_ext['member_id'] = $this->_memberId;
            DB::SetMainDB(DB_MAIN);
            $extid = DB::result_first('select id from %t where mid=%s and logid=%d and actid=%d and display=1',array('wx_act_ext',$this->_mid,$insert_id,$k));
            if($extid){
                $insert_ext['updatetime'] = TIME;
                DB::SetMainDB(DB_MAIN);
                DB::update('wx_act_ext',$insert_ext,array('mid'=>$this->_mid,'id'=>$extid));
            }else{
                $insert_ext['logid'] = $insert_id; 
                $insert_ext['inputtime'] = TIME;
                $insert_ext['mid'] = $this->_mid;
                $insert_ext['tablename'] = $ordername;
                $insert_ext['tableid'] = $orderid;
                $insert_ext['status'] = 1;
                $insert_ext['display'] = 1;
                DB::SetMainDB(DB_MAIN);
                DB::insert('wx_act_ext',$insert_ext,true);
            }
        }

        if(($this->_openid || $this->_memberId) && $insert_id){
            $this->form_pub($public);
        }
        
        return true;
    }
    
    //存储公共的表单
    private function form_pub($public=array()){
        if((!$this->_openid && !$this->_memberId) || empty($public)) return false;
        foreach($public as $k=>$v){
            if(empty($v['actpid']) || empty($v['value'])) continue;
            $memberWhere = C::t("#api#user")->memberWhere($this->_openid,$this->_memberId);
            $insert = array();
            DB::SetMainDB(DB_MAIN);
            $pub = DB::fetch_first('select id,`usage` from %t where mid=%s %i and actpid=%d and value=%s and display=1',array('wx_act_ext_pub',$this->_mid,$memberWhere,$v['actpid'],$v['value']));
            if($pub['id']){
                $insert['usage'] = $pub['usage'] + 1;
                $insert['updatetime'] = TIME;
                DB::SetMainDB(DB_MAIN);
                DB::update('wx_act_ext_pub',$insert,array('mid'=>$this->_mid,'id'=>$pub['id']));
            }else{
                $insert = $v;
                $insert['mid'] = $this->_mid;
                $insert['openid'] = $this->_openid;
                $insert['member_id'] = $this->_memberId;
                $insert['usage'] = 1;
                $insert['inputtime'] = TIME;
                $insert['status'] = 1;
                $insert['display'] = 1;
                DB::SetMainDB(DB_MAIN);
                DB::insert('wx_act_ext_pub',$insert,true);
            }
            $insert = array();
        }
    }
    
    //初始化微信用户数据
    public function shakeUser($nowArr=array()){ //allCount：已经摇奖数，yesgetNUm：中奖数
        echo "shake_id:".$this->_shake_id."<br>";
        if($nowArr){
            $thisData = $this->dataTurn($nowArr);
            redis2("set","shakeUser-".$this->_openid."-".$this->_shake_id,$thisData);
        }else{
            $user = redis2("get","shakeUser-".$this->_openid."-".$this->_shake_id);
            return $this->dataTurn($user,"get");
        }
    }
}
?>